package org.example.leetcode;

/**
 * 两数相加 : <a href="https://leetcode.cn/problems/add-two-numbers/">...</a>
 *
 * @Author ZSL
 * @Date 2022/9/28 15:31
 * @Version 1.0
 */
public class Two2 {

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }


    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode begin = new ListNode();
        ListNode index = begin;
        int i = 0;
        while (l1 != null || l2 != null) {
            int temp1 = l1 == null ? 0 : l1.val;
            int temp2 = l2 == null ? 0 : l2.val;
            int sum = temp2 + temp1 + i;
            i = sum > 9 ? 1 : 0;
            sum = sum % 10;

            index.next = new ListNode(sum);

            index = index.next;
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }

            if (i == 1) {
                index.next = new ListNode(i);
            }
        }
        return begin.next;
    }
}
